<template>
  <view>
    <u-button @click="state.pickShow = true">选择时间</u-button>
    <u-popup :show="state.pickShow" :round="10" mode="bottom" @close="toClose">
      <view class="z-popup">
        <view class="title">选择月份</view>
        <scroll-view :scroll-y="true" class="z-scroll-view">
          <picker-view indicator-style="height: 50px" :value="state.initValue" @change="bindChange" class="picker-view">
            <picker-view-column>
              <view class="item" v-for="(item,index) in years" :key="index">{{item}}年</view>
            </picker-view-column>
            <picker-view-column>
              <view class="item" v-for="(item,index) in months" :key="index">{{item}}月</view>
            </picker-view-column>
            <picker-view-column>
              <view class="item" v-for="(item,index) in days" :key="index">{{item}}日</view>
            </picker-view-column>
          </picker-view>
        </scroll-view>
        <u-button @click="toSubmit">提交</u-button>
      </view>
    </u-popup>
  </view>
</template>

<script setup>
const state = reactive({
  pickShow: false,
  initValue: [9999, new Date().getMonth(), new Date().getDate() - 1],
  year: new Date().getFullYear(),
  month: new Date().getMonth(),
  day: new Date().getDay()
})
const years = computed(() => initTimeData(new Date().getFullYear(), 2013))
const months = computed(() => initTimeData(12, 1))
const days = computed(() => initTimeData(getOneMonthDays(state.year, state.month), 1))
const bindChange = ({ detail: { value } }) => {
  /*
  * 重点是这里
  * 这里拿到的是下标
  * 赋初始值也是下标
  * 数组就是 years/months/days
  * */
  state.year = value[0]
  state.month = value[1]
  state.day = value[2]
}
const toSubmit = () => {
  const value = [years.value[state.year], addZero(months.value[state.month]), addZero(days.value[state.day])].join('-')
  console.info(value, '---')
}
const getOneMonthDays = (year,month)=>{
  month = Number(month);
  const baseMonthsDays = [31,28,31,30,31,30,31,31,30,31,30,31];
  if(year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)){
    if(month === 2){
      baseMonthsDays[month] = 29;
    }
  }
  return baseMonthsDays[month];
}
const initTimeData = (end, start) => {
  const timeArray = []
  while (start <= end) {
    timeArray.push(start)
    start++
  }
  return timeArray
}
const addZero = number => {
  if (number.toString().length < 2) return '0' + number
  else return number.toString()
}
const toClose = () => {
  state.pickShow = false
}
</script>

<style lang="scss" scoped>
.z-popup{
  .title {
    text-align: center;
  }
  .z-scroll-view {
    margin: 0 40rpx;
    height: 60vh;
  }
  .button{
    padding: 40rpx;
  }
  .picker-view {
    width: 750rpx;
    height: 600rpx;
    margin-top: 20rpx;
  }
  .item {
    line-height: 100rpx;
    text-align: center;
  }
}
</style>
